// Written in the D Programming Language
/**
 * The 12th lesson in the <a href="http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=12">NeHe tutorial series</a>.
 * Originally written by Jeff Molofee.
 *
 * Authors: Jeff Molofee
 *          Olli Aalto
 */
module lesson12;

import derelict.opengl.gl;
import derelict.opengl.glu;
import derelict.sdl.sdl;

import tango.stdc.stringz;

/// The window title
const char[] WINDOW_TITLE = "NeHe's Display List Tutorial (D version)";

/// The main loop flag
bool running = true;

/// Storage For One Texture
GLuint texture;
/// Storage For The Box Display List
GLuint box;
/// Storage For The Top Display List
GLuint top;
/// Loop For X Axis
GLuint xloop;
/// Loop For Y Axis
GLuint yloop;

/// Rotates Cube On The X Axis
GLfloat xrot = 0.0f;
/// Rotates Cube On The Y Axis
GLfloat yrot = 0.0f;

/// Array For Box Colors
GLfloat boxcol[5][3] = [[1.0f, 0.0f, 0.0f], [1.0f, 0.5f, 0.0f], [1.0f, 1.0f,
	0.0f], [0.0f, 1.0f, 0.0f], [0.0f, 1.0f, 1.0f]];

/// Array For Top Colors
GLfloat topcol[5][3] = [[0.5f, 0.0f, 0.0f], [0.5f, 0.25f, 0.0f], [0.5f, 0.5f,
	0.0f], [0.0f, 0.5f, 0.0f], [0.0f, 0.5f, 0.5f]];

/**
 * Module constructor. Here we load the GL, GLU and SDL shared libraries,
 * and the initialize SDL.
 */
static this()
{
	DerelictGL.load();
	DerelictGLU.load();
	DerelictSDL.load();

	if (SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		throw new Exception("Failed to initialize SDL: " ~ getSDLError());
	}
	// Enable key repeating
	if ((SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY,
		SDL_DEFAULT_REPEAT_INTERVAL)))
	{
		throw new Exception("Failed to set key repeat: " ~ getSDLError());
	}
}

/**
 * Module destructor. SDL_Quit must be called somewhere, and as we initialized
 * it in the module constructor so the module destructor should be a suitable
 * place.
 */
static ~this()
{
	SDL_Quit();
}

/**
 * The main function. This is where the fun begins. The first order of business
 * is the check the command line arguments if the user wanted to start in
 * fullscreen mode. Then the window is created and OpenGL is initialized with
 * basic settings. Finally the the function starts the main loop which will live
 * for the duration of the application.
 *
 * Params:
 *      args = the command line arguments
 */
void main(char[][] args)
{
	bool fullScreen = false;

	if (args.length > 1)
	{
		fullScreen = args[1] == "-fullscreen";
	}

	createGLWindow(WINDOW_TITLE, 640, 480, 16, fullScreen);
	initGL();

	while (running)
	{
		processEvents();

		drawGLScene();

		SDL_GL_SwapBuffers();
		SDL_Delay(10);
	}
}

/**
 * Build Box Display List.
 */
void buildLists()
{
	// Generate 2 Different Lists
	box = glGenLists(2);
	// Start With The Box List
	glNewList(box, GL_COMPILE);
	{
		glBegin(GL_QUADS);
		{
			// Bottom Face
			glNormal3f(0.0f, -1.0f, 0.0f);
			glTexCoord2f(1.0f, 1.0f);
			glVertex3f(-1.0f, -1.0f, -1.0f);
			glTexCoord2f(0.0f, 1.0f);
			glVertex3f(1.0f, -1.0f, -1.0f);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(1.0f, -1.0f, 1.0f);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(-1.0f, -1.0f, 1.0f);

			// Front Face
			glNormal3f(0.0f, 0.0f, 1.0f);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(-1.0f, -1.0f, 1.0f);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(1.0f, -1.0f, 1.0f);
			glTexCoord2f(1.0f, 1.0f);
			glVertex3f(1.0f, 1.0f, 1.0f);
			glTexCoord2f(0.0f, 1.0f);
			glVertex3f(-1.0f, 1.0f, 1.0f);

			// Back Face
			glNormal3f(0.0f, 0.0f, -1.0f);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(-1.0f, -1.0f, -1.0f);
			glTexCoord2f(1.0f, 1.0f);
			glVertex3f(-1.0f, 1.0f, -1.0f);
			glTexCoord2f(0.0f, 1.0f);
			glVertex3f(1.0f, 1.0f, -1.0f);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(1.0f, -1.0f, -1.0f);

			// Right face
			glNormal3f(1.0f, 0.0f, 0.0f);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(1.0f, -1.0f, -1.0f);
			glTexCoord2f(1.0f, 1.0f);
			glVertex3f(1.0f, 1.0f, -1.0f);
			glTexCoord2f(0.0f, 1.0f);
			glVertex3f(1.0f, 1.0f, 1.0f);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(1.0f, -1.0f, 1.0f);

			// Left Face
			glNormal3f(-1.0f, 0.0f, 0.0f);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(-1.0f, -1.0f, -1.0f);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(-1.0f, -1.0f, 1.0f);
			glTexCoord2f(1.0f, 1.0f);
			glVertex3f(-1.0f, 1.0f, 1.0f);
			glTexCoord2f(0.0f, 1.0f);
			glVertex3f(-1.0f, 1.0f, -1.0f);
		}
		glEnd();
	}
	glEndList();

	// Storage For "Top" Is "Box" Plus One
	top = box + 1;
	// Now The "Top" Display List
	glNewList(top, GL_COMPILE);
	{
		glBegin(GL_QUADS);
		{
			// Top Face
			glNormal3f(0.0f, 1.0f, 0.0f);
			glTexCoord2f(0.0f, 1.0f);
			glVertex3f(-1.0f, 1.0f, -1.0f);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(-1.0f, 1.0f, 1.0f);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(1.0f, 1.0f, 1.0f);
			glTexCoord2f(1.0f, 1.0f);
			glVertex3f(1.0f, 1.0f, -1.0f);
		}
		glEnd();
	}
	glEndList();
}

/**
 * function to load in bitmap as a GL texture.
 */
void loadGLTextures()
{
	/* Create storage space for the texture */
	SDL_Surface* textureImage;

	/* Load The Bitmap, Check For Errors, If Bitmap's Not Found Quit */
	if ((textureImage = SDL_LoadBMP("data/Cube.bmp")) !is null)
	{
		// Free the surface when exiting the scope
		scope(exit)
			SDL_FreeSurface(textureImage);

		/* Create The Texture */
		glGenTextures(1, &texture);

		/* Typical Texture Generation Using Data From The Bitmap */
		glBindTexture(GL_TEXTURE_2D, texture);

		/* Linear Filtering */
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

		/* Generate The Texture */
		glTexImage2D(GL_TEXTURE_2D, 0, 3, textureImage.w, textureImage.h, 0,
			GL_BGR, GL_UNSIGNED_BYTE, textureImage.pixels);

		return;
	}
	throw new Exception("Failed to load texture.");
}

/**
 * Process all the pending events.
 */
void processEvents()
{
	SDL_Event event;
	while (SDL_PollEvent(&event))
	{
		switch (event.type)
		{
			case SDL_KEYUP:
				keyReleased(event.key.keysym.sym);
				break;
			case SDL_KEYDOWN:
				keyPressed(event.key.keysym.sym);
				break;
			case SDL_QUIT:
				running = false;
				break;
			default:
				break;
		}
	}
}

/**
 * Process a key pressed event.
 */
void keyPressed(int key)
{
	switch (key)
	{
		case SDLK_RIGHT:
			yrot += 0.2f;
			break;
		case SDLK_LEFT:
			yrot -= 0.2f;
			break;
		case SDLK_DOWN:
			xrot += 0.2f;
			break;
		case SDLK_UP:
			xrot -= 0.2f;
			break;
		default:
			break;
	}
}

/**
 * Process a key released event.
 */
void keyReleased(int key)
{
	if (key == SDLK_ESCAPE)
	{
		running = false;
	}
}

/**
 * Resize And Initialize The GL Window.
 */
void resizeGLScene(GLsizei width, GLsizei height)
{
	if (height == 0)
	{
		height = 1;
	}
	// Reset The Current Viewport
	glViewport(0, 0, width, height);

	// Select The Projection Matrix
	glMatrixMode(GL_PROJECTION);
	// Reset The Projection Matrix
	glLoadIdentity();

	// Calculate The Aspect Ratio Of The Window
	gluPerspective(45.0f, cast(GLfloat) width / cast(GLfloat) height, 0.1f,
		100.0f);

	// Select The Modelview Matrix
	glMatrixMode(GL_MODELVIEW);
	// Reset The Modelview Matrix
	glLoadIdentity();
}

/**
 * All Setup For OpenGL Goes Here.
 */
void initGL()
{
	loadGLTextures();
	buildLists();

	// Enable Texture Mapping ( NEW )
	glEnable(GL_TEXTURE_2D);
	// Enables Smooth Shading
	glShadeModel(GL_SMOOTH);
	// Black Background
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	// Depth Buffer Setup
	glClearDepth(1.0f);
	// Enables Depth Testing
	glEnable(GL_DEPTH_TEST);
	// The Type Of Depth Test To Do
	glDepthFunc(GL_LEQUAL);
	// Really Nice Perspective Calculations
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
	// Quick And Dirty Lighting (Assumes Light0 Is Set Up)
	glEnable(GL_LIGHT0);
	// Enable Lighting
	glEnable(GL_LIGHTING);
	// Enable Material Coloring
	glEnable(GL_COLOR_MATERIAL);

	// Change to texture matrix and flip and rotate the texture
	glMatrixMode(GL_TEXTURE);
	glRotatef(180.0f, 0.0f, 0.0f, 1.0f);
	glScalef(-1.0f, 1.0f, 1.0f);
	// Back to normal
	glMatrixMode(GL_MODELVIEW);
}

/**
 * Here's Where We Do All The Drawing.
 */
void drawGLScene()
{
	// Clear The Screen And The Depth Buffer
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glBindTexture(GL_TEXTURE_2D, texture);

	// Loop Through The Y Plane
	for (yloop = 1; yloop < 6; yloop++)
	{
		// Loop Through The X Plane
		for (xloop = 0; xloop < yloop; xloop++)
		{
			// Reset The View
			glLoadIdentity();
			// Position The Cubes On The Screen
			glTranslatef(1.4f + (xloop * 2.8f) - (yloop * 1.4f),
				((6.0f - yloop) * 2.4f) - 7.0f, -20.0f);
			// Tilt The Cubes Up And Down
			glRotatef(45.0f - (2.0f * yloop) + xrot, 1.0f, 0.0f, 0.0f);
			// Spin Cubes Left And Right
			glRotatef(45.0f + yrot, 0.0f, 1.0f, 0.0f);

			// Select A Box Color
			glColor3fv(boxcol[yloop - 1].ptr);
			// Draw The Box
			glCallList(box);

			// Select The Top Color
			glColor3fv(topcol[yloop - 1].ptr);
			// Draw The Top
			glCallList(top);
		}
	}
}

void createGLWindow(char[] title, int width, int height, int bits,
	bool fullScreen)
{
	// Set the OpenGL attributes
	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	// Set the window title
	SDL_WM_SetCaption(toStringz(title), null);

	/* Note the SDL_DOUBLEBUF flag is not required to enable double
	 * buffering when setting an OpenGL video mode.
	 * Double buffering is enabled or disabled using the
	 * SDL_GL_DOUBLEBUFFER attribute.
	 */
	int mode = SDL_OPENGL;
	if (fullScreen)
	{
		mode |= SDL_FULLSCREEN;
	}
	// Now open a SDL OpenGL window with the given parameters
	if (SDL_SetVideoMode(width, height, bits, mode) is null)
	{
		throw new Exception("Failed to open OpenGL window: " ~ getSDLError());
	}

	resizeGLScene(width, height);
}

/**
 * Get the SDL error as a D string.
 *
 * Returns: A D string containing the current SDL error.
 */
char[] getSDLError()
{
	return fromStringz(SDL_GetError());
}
